package com.example.questionsystem.modules.qu.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.NameFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.questionsystem.modules.qu.Vo.PackageVo;
import com.example.questionsystem.modules.qu.dto.*;
import com.example.questionsystem.modules.qu.entity.*;
import com.example.questionsystem.modules.qu.enums.QuestionTypeEnum;
import com.example.questionsystem.modules.qu.mapper.QuestionBankMapper;
import com.example.questionsystem.modules.qu.service.PackageService;
import com.example.questionsystem.modules.qu.service.ProjectsService;
import com.example.questionsystem.modules.qu.service.SubjectsService;

import com.example.questionsystem.modules.qu.service.util.AdvancedContentExtractor2;
import com.example.questionsystem.modules.qu.service.util.ChineseNumberConverter;
import com.example.questionsystem.modules.qu.util.AESDecryptor;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.CompressionLevel;
import net.lingala.zip4j.model.enums.CompressionMethod;
import net.lingala.zip4j.model.enums.EncryptionMethod;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static com.example.questionsystem.modules.qu.util.FileUtils.deleteDirectory;

/**
 * 打包服务实现类
 */
@Service
public class PackageServiceImpl implements PackageService {


    @Value("${question.storage.temp-dir}")
    private String tempDirPath;

    @Resource
    private ProjectsService projectsService;

    @Resource
    private SubjectsService subjectsService;

    @Resource
    private QuestionBankServiceImpl questionBanksService;


    @Resource
    private ZipService zipService;

    @Override
    public void generateSession(PackageVo request) throws IOException {
        Projects project = projectsService.getById(request.getProjectId());
        String sessionName = request.getSessionName();
        String sessionNumber = ChineseNumberConverter.extractAndConvertChineseNumber(sessionName);
        List<PackageSessions> subjects = request.getSubjects();
        // 新增代码：处理 final 目录下的文件夹

            Path finalDir = Paths.get(request.getOutputPath() + "/final");
            List<Path> targetDirs = new ArrayList<>();

            try (DirectoryStream<Path> stream = Files.newDirectoryStream(finalDir)) {
                for (Path path : stream) {
                    if (Files.isDirectory(path)) {
                        String dirName = path.getFileName().toString();
                        subjects.forEach(subject -> {
                            if (dirName.equals(subject.getSubjectId() )) {
                                targetDirs.add(finalDir.resolve(subject.getSubjectId() ));
                            }
                        });
                    }
                }
            }

            // 创建临时目录存放中间压缩包
            Path tempDir = createTempDirectory("session_packages");

            // 直接压缩所有匹配的文件夹到最终压缩包
            try (OutputStream os = Files.newOutputStream(Paths.get(request.getOutputPath() + "/" +  "dzsjb_"+project.getProjectId() +"_"+ChineseNumberConverter.extractAndConvertChineseNumber(sessionName)  + ".zip"))) {
                zipService.createEncryptedZipFromDirs(targetDirs, os, request.getPassword());
            }

            // 清理临时目录
            deleteDirectory(tempDir);


    }

    @Override
    public void generateSessionEncrypted(PackageVo request, HttpServletResponse response) throws Exception {
        Projects project = projectsService.getById(request.getProjectId());
        List<Path> paths = new ArrayList<>();
        // 遍历科目信息
        request.getSubjects().forEach(PackageSubject -> {
            // 2. 获取基础数据
            SubjectSessions subjectSessions = subjectsService.getSubjectSessionsById(PackageSubject.getSubjectId());

            Path subjectsDir = null;
            try {
                String sessionName = subjectSessions.getSessionName();
                subjectsDir = createTempDirectory(project.getProjectId() + "_"+ subjectSessions.getKmxh() + "_" + ChineseNumberConverter.extractAndConvertChineseNumber(sessionName) );
                Path imageDir = subjectsDir.resolve("files");
                Files.createDirectories(imageDir);



                // 检查 files 文件夹是否有内容
                try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(imageDir)) {
                    if (directoryStream.iterator().hasNext()) {
                        // 压缩 files 文件夹
                        Path filesZip = subjectsDir.resolve("files.zip");
                        zipService.createEncryptedZipFromDir(imageDir, Files.newOutputStream(filesZip), request.getPassword());

                        // 删除原始的 files 文件夹
                        deleteDirectory(imageDir);
                    } else {
                        // files 文件夹为空，删除空文件夹
                        Files.deleteIfExists(imageDir);
                    }
                }
                paths.add(subjectsDir);

            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        });

        // 修改压缩部分
        try {
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=session_encrypted_package.zip");

            // 创建临时主目录
            Path mainTempDir = createTempDirectory("session_encrypted_main");
            try {
                // 将所有科目目录移动到主目录下
                for (Path dir : paths) {
                    Path target = mainTempDir.resolve(dir.getFileName());
                    Files.move(dir, target, StandardCopyOption.REPLACE_EXISTING);
                }

                // 加密压缩整个主目录
                zipService.createEncryptedZipFromDir(mainTempDir, response.getOutputStream(), request.getPassword());
            } finally {
                deleteDirectory(mainTempDir);
            }
        } finally {
            // 清理所有原始临时目录
            paths.forEach(dir -> {
                try {
                    if (Files.exists(dir)) {
                        deleteDirectory(dir);
                    }
                } catch (IOException e) {
                    // 记录日志
                }
            });
        }

    }

    // 试考报
    @Override
    public void generateExamOldPackage(PackageRequest request, HttpServletResponse response) throws Exception {

        // 2. 获取基础数据
        Projects project = projectsService.getById(request.getSelectedProjectId());
        SubjectSessions subject = subjectsService.getSubjectSessionsById(request.getSelectedSubjectId());
        if (!subject.getSessionName().equals(request.getSessionName())) {
            throw new TotalScoreMismatchException("当前科目所属场次与选中场次不一致");
        }
        List<QuestionBanks> allQuestions = questionBanksService.getQuestionBanksBySubjectId(request.getSelectedSubjectId());

        // 4. 创建临时目录
        Path tempDir = createTempDirectory(tempDirPath);
        Path imageDir = tempDir.resolve("files");
        Files.createDirectories(imageDir);
        // 分数入库
       // setQuestionScore(request);
        Path tempZip = null;
        try {
            // 5. 生成配置文件
            generatePageFile(project,subject,request,allQuestions,tempDir,imageDir);
            generateLoginFile(tempDir);

            //  打包压缩到临时文件
             tempZip = Files.createTempFile("package", ".zip");
            try (OutputStream outputStream = Files.newOutputStream(tempZip)) {
                zipService.createEncryptedZipFromDir(tempDir, outputStream, request.getPassword());
            }

            // 拷贝压缩包到目标目录
            Path targetDir = Paths.get(request.getOutputPath() + "/check/" + subject.getSubjectId() );
            Files.createDirectories(targetDir);
            Path targetZip = targetDir.resolve("单机测试考试包.zip");
            Files.copy(tempZip, targetZip, StandardCopyOption.REPLACE_EXISTING);

            // 将生成的压缩包写入响应流
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=" + subject.getSubjectId() + ".zip");
            Files.copy(tempZip, response.getOutputStream());

            // 7. 打包压缩
            zipService.createEncryptedZipFromDir(tempDir, response.getOutputStream(), request.getPassword());

        } finally {
            deleteDirectory(tempDir);
            if (tempZip != null) {
                Files.deleteIfExists(tempZip); // 现在可以访问tempZip变量
            }
        }
    }

    @Resource
    private QuestionBankMapper questionBankMapper;
    @Override
    public void generateExamOldFormalPackage(PackageRequest request, HttpServletResponse response) throws Exception {
        Projects project = projectsService.getById(request.getSelectedProjectId());
        SubjectSessions subject = subjectsService.getSubjectSessionsById(request.getSelectedSubjectId());
        if (!subject.getSessionName().equals(request.getSessionName())) {
            throw new TotalScoreMismatchException("当前科目所属场次与选中场次不一致");
        }
        // 分数入库
        setQuestionScore(request);

        List<QuestionBanks> allQuestions = questionBanksService.getQuestionBanksBySubjectId(request.getSelectedSubjectId());
        // 4. 创建临时目录
        Path tempDir = createTempDirectory(tempDirPath);
        Path imageDir = tempDir.resolve("files");
        Files.createDirectories(imageDir);
        Path tempZip = null;
        try {
            // 5. 生成配置文件
            generatePageFormalFile(project,subject,request,allQuestions,tempDir,imageDir);
            generateQuestionInformation(allQuestions,request,request.getOutputPath() + "/check/" +subject.getSubjectId(),imageDir);

            // 对 files 文件夹中的文件进行压缩
            Path encryptedFilesZip = tempDir.resolve("files.zip");
            ZipParameters zipParameters = new ZipParameters();
            ZipFile zipFile = new ZipFile(encryptedFilesZip.toFile());

            // 遍历 files 文件夹下的文件并添加到压缩包
            try (Stream<Path> paths = Files.walk(imageDir)) {
                paths.filter(Files::isRegularFile).forEach(file -> {
                    try {
                        // 获取相对路径，避免将完整路径添加到压缩包
                        Path relativePath = imageDir.relativize(file);
                        // 修改添加文件的方式
                        zipParameters.setFileNameInZip(relativePath.toString());
                        zipFile.addFile(file.toFile(), zipParameters);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
            }

            // 删除原始的 files 文件夹
            deleteDirectory(imageDir);
            // 创建一个新文件夹用于存放压缩包和配置文件
            Path finalPackageDir = tempDir.resolve(subject.getSubjectId());
            Files.createDirectories(finalPackageDir);

            // 新增: 在压缩前拷贝文件目录
            Path targetDir = Paths.get(request.getOutputPath() + "/check/" +subject.getSubjectId()+"/paper/");
            Files.createDirectories(targetDir);
            Path targetFinal  = Paths.get(request.getOutputPath() + "/final/" +subject.getSubjectId());
            Files.createDirectories(targetFinal);
            // 拷贝临时目录所有内容到目标目录
            try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(tempDir)) {
                for (Path firstLevelPath : dirStream) {
                    if (Files.isDirectory(firstLevelPath)) {
                        // 处理文件夹，只拷贝文件夹内的内容
                        try (Stream<Path> stream = Files.walk(firstLevelPath).skip(1)) {
                            stream.forEach(source -> {
                                try {
                                    // 计算相对于一级子目录的相对路径
                                    Path relativePath = firstLevelPath.relativize(source);
                                    Path destination = targetDir.resolve(relativePath);
                                    Path finalDestination = targetFinal.resolve(relativePath);
                                    if (Files.isDirectory(source)) {
                                        Files.createDirectories(destination);
                                        Files.createDirectories(finalDestination);
                                    } else {
                                        Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
                                        Files.copy(firstLevelPath, finalDestination, StandardCopyOption.REPLACE_EXISTING);
                                    }
                                } catch (IOException e) {
                                    throw new RuntimeException("文件拷贝失败: " + e.getMessage(), e);
                                }
                            });
                        }
                    } else {
                        // 处理文件，直接拷贝
                        Path destination = targetDir.resolve(firstLevelPath.getFileName());
                        Path finalDestination = targetFinal.resolve(firstLevelPath.getFileName());
                        Files.copy(firstLevelPath, destination, StandardCopyOption.REPLACE_EXISTING);
                        Files.copy(firstLevelPath, finalDestination, StandardCopyOption.REPLACE_EXISTING);
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException("文件拷贝失败: " + e.getMessage(), e);
            }


        } finally {
            deleteDirectory(tempDir);
            if (tempZip != null) {
                Files.deleteIfExists(tempZip); // 清理临时文件
            }
        }
    }

    @Override
    public void generateUseCountPackage(ExtractionConfigDto requestData, HttpServletResponse response) throws IOException {
        // 2. 获取基础数据
        Projects project = projectsService.getById(requestData.getSelectedProjectId());
        SubjectSessions subject = subjectsService.getSubjectSessionsById(requestData.getSelectedSubjectId());
        List<QuestionBanks> allQuestions = questionBanksService.extractQuestions(requestData.getExtractionConfigs());

        // 4. 创建临时目录
        Path tempDir = createTempDirectory(tempDirPath);
        Path imageDir = tempDir.resolve("files");
        Files.createDirectories(imageDir);
        Path tempZip = null;
        try {
            // 5. 生成配置文件
            //generateUseCountPageFile(project,subject,requestData,allQuestions,tempDir,imageDir);
            //generateLoginFile(tempDir);

            //  打包压缩到临时文件
            tempZip = Files.createTempFile("package", ".zip");
            try (OutputStream outputStream = Files.newOutputStream(tempZip)) {
                zipService.createEncryptedZipFromDir(tempDir, outputStream, requestData.getPassword());
            }

            // 拷贝压缩包到目标目录
            Path targetDir = Paths.get("C:/kz/check/" + subject.getSubjectId() );
            Files.createDirectories(targetDir);
            Path targetZip = targetDir.resolve("单机测试考试包.zip");
            Files.copy(tempZip, targetZip, StandardCopyOption.REPLACE_EXISTING);

            // 将生成的压缩包写入响应流
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=" + subject.getSubjectId() + ".zip");
            Files.copy(tempZip, response.getOutputStream());

            // 7. 打包压缩
            zipService.createEncryptedZipFromDir(tempDir, response.getOutputStream(), requestData.getPassword());

        } finally {
            deleteDirectory(tempDir);
            if (tempZip != null) {
                Files.deleteIfExists(tempZip); // 现在可以访问tempZip变量
            }
        }
    }
    // 清除questionHtml <p>标签 内容是 &nbsp;
    public static String cleanQuestionHtml(String questionHtml) {
        Document parse = Jsoup.parse(questionHtml);
        Elements pElements = parse.select("p");
        for (Element p : pElements) {
            // 改为检查Unicode空格字符
            if (p.text().trim().equals("\u00A0") || p.text().trim().isEmpty()) {
                p.remove();
            }
        }
        return parse.body().html();
    }



    @Transactional(rollbackFor = Exception.class)
    public  void setQuestionScore( PackageRequest request) throws Exception {
        // 根据设置的分值，计算出每道题的分值，并且存入数据库
        request.getQuestionTypes().forEach(questionType -> {
            if (questionType.getQuestionType().equals("判断题")){
                questionType.getScoreList().forEach(scoreList -> {
                        QuestionBanks questionBank = questionBanksService.getByQuestionId(scoreList.getQuestionId());
                        questionBank.setScore(String.valueOf(scoreList.getScore()));;
                        questionBanksService.updateScoreByQuestionId(questionBank);
                });
            }
        });
        request.getQuestionTypes().forEach(questionType -> {
            if (questionType.getQuestionType().equals("单项选择题")){
                questionType.getScoreList().forEach(scoreList -> {
                        QuestionBanks questionBank = questionBanksService.getByQuestionId(scoreList.getQuestionId());
                        questionBank.setScore(String.valueOf(scoreList.getScore()));;
                        questionBanksService.updateScoreByQuestionId(questionBank);
                });
            }
        });
        request.getQuestionTypes().forEach(questionType -> {
            if (questionType.getQuestionType().equals("多项选择题")){
                questionType.getScoreList().forEach(scoreList -> {
                        QuestionBanks questionBank = questionBanksService.getByQuestionId(scoreList.getQuestionId());
                        questionBank.setScore(String.valueOf(scoreList.getScore()));;
                        questionBanksService.updateScoreByQuestionId(questionBank);
                });
            }
        });
        request.getQuestionTypes().forEach(questionType -> {
            if (questionType.getQuestionType().equals("不定项")){
                questionType.getScoreList().forEach(scoreList -> {
                    QuestionBanks questionBank = questionBanksService.getByQuestionId(scoreList.getQuestionId());
                    questionBank.setScore(String.valueOf(scoreList.getScore()));;
                    questionBanksService.updateScoreByQuestionId(questionBank);
                });
            }
        });
        request.getQuestionTypes().forEach(questionType -> {
            if (questionType.getQuestionType().equals("填空题")){
                questionType.getScoreList().forEach(scoreList -> {
                    QuestionBanks questionBank = questionBanksService.getByQuestionId(scoreList.getQuestionId());
                    questionBank.setScore(String.valueOf(scoreList.getScore()));;
                    questionBanksService.updateScoreByQuestionId(questionBank);
                });
            }
        });
        request.getQuestionTypes().forEach(questionType -> {
            if (questionType.getQuestionType().equals("简答题")){
                questionType.getScoreList().forEach(scoreList -> {
                    QuestionBanks questionBank = questionBanksService.getByQuestionId(scoreList.getQuestionId());
                    questionBank.setScore(String.valueOf(scoreList.getScore()));;
                    questionBanksService.updateScoreByQuestionId(questionBank);
                });
            }
        });
        request.getQuestionTypes().forEach(questionType -> {
            if (questionType.getQuestionType().equals("表格题")){
                questionType.getScoreList().forEach(scoreList -> {
                        QuestionBanks questionBank = questionBanksService.getByQuestionId(scoreList.getQuestionId());
                        questionBank.setScore(String.valueOf(scoreList.getScore()));;
                        questionBanksService.updateScoreByQuestionId(questionBank);
                });
            }
        });
        request.getQuestionTypes().forEach(questionType -> {
            if (questionType.getQuestionType().equals("综合题")){
                questionType.getScoreList().forEach(scoreList -> {
                        QuestionBanks questionBank = questionBanksService.getByQuestionId(scoreList.getQuestionId());
                        questionBank.setScore(String.valueOf(scoreList.getScore()));;
                        questionBanksService.updateScoreByQuestionId(questionBank);
                });
            }
        });
        //写作题
        request.getQuestionTypes().forEach(questionType -> {
            if (questionType.getQuestionType().equals("写作题")){
                questionType.getScoreList().forEach(scoreList -> {
                        QuestionBanks questionBank = questionBanksService.getByQuestionId(scoreList.getQuestionId());
                        questionBank.setScore(String.valueOf(scoreList.getScore()));;
                        questionBanksService.updateScoreByQuestionId(questionBank);
                });
            }
        });


    }
    private JSONObject generateQuestionInformation(List<QuestionBanks> allQuestions, PackageRequest request,String filePath,Path imageDir) throws Exception {
        JSONObject config = new JSONObject(new LinkedHashMap<>());
        // 题目信息
        List<quesDtos> quesDtosList = new ArrayList<>();
        for (QuestionBanks question : allQuestions) {
            quesDtos q = new quesDtos();
            q.setId(0);
            q.setProjectId(0);
            q.setLibraryId("");
            q.setParentId("");
            q.setChildCount(0);
            q.setInputType(0);
            q.setDifficultLevel(0);
            q.setQuesAnswer("");
            q.setQuesNo(question.getQuestionId());
            q.setQuesScore(Double.parseDouble(question.getScore()));
            if (question.getQuestionType().equals("判断题")){
                q.setQuesType(1);
            }
            if (question.getQuestionType().equals("单项选择题")){
                q.setQuesType(2);
            }
            if (question.getQuestionType().equals("多项选择题")){
                q.setQuesType(3);
            }
            if (question.getQuestionType().equals("不定项")){
                q.setQuesType(4);
            }
            if (question.getQuestionType().equals("计算题")){
                q.setQuesType(6);
            }
            if (question.getQuestionType().equals("填空题")){
                q.setQuesType(5);
            }
            if (question.getQuestionType().equals("简答题")){
                q.setQuesType(6);
            }
            if (question.getQuestionType().equals("表格题")){
                q.setQuesType(11);
            }
            if (question.getQuestionType().equals("综合题")){
                q.setQuesType(10);
            }
            String[] s = question.getQuestionId().split("_");
            q.setSort(Integer.parseInt(s[s.length-1]));
            List<files> Fileslist = new ArrayList();
            q.setFiles("[]");
            q.setQuesTitle(question.getQuestionHtml());
            List<Options> optionHTMLList = Options.parseOptionsHTML(question.getOptionsHtml(), request.getEncryptPassword());
            q.setOptions(JSON.toJSONString(optionHTMLList));
            quesDtosList.add(q);


        }
        config.put("quesItems", quesDtosList);

        // 自定义 NameFilter，直接返回原始属性名
        NameFilter nameFilter = (object, name, value) -> name;

        // 使用自定义 NameFilter 进行序列化
        String jsonString = JSON.toJSONString(config, nameFilter, SerializerFeature.PrettyFormat);
        Path userDirPath = Paths.get(filePath);
        Files.createDirectories(userDirPath);

        // 定义要保存的文件名

        // 写入文件
        Files.write(userDirPath.resolve("question.txt"),
                jsonString.getBytes(StandardCharsets.UTF_8));
        return config;
    }
    /**
     *  生成正式试考包
     * @param project
     * @param subject
     * @param request
     * @param questions
     * @param tempDir
     * @param imageDir
     * @return
     * @throws Exception
     */
    private JSONObject generatePageFormalFile(Projects project,
                                              SubjectSessions subject,
                                              PackageRequest request,
                                              List<QuestionBanks> questions,
                                              Path tempDir,
                                              Path imageDir) throws Exception {

        JSONObject config = new JSONObject(new LinkedHashMap<>());
        int questionCount = questionBanksService.getQuestionCountBySubjectId(subject.getSubjectId());
        // 1. 生成配置文件
        PaperDesc paperDesc = PaperDesc.builder()
                .TotalScore(request.getTotalScore())
                .TotalCount(questionCount)
                .TotalNeedCount(questionCount)
                .Kmxh(subject.getKmxh())
                .MakeupPaperType(0)
                .JudgeCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("判断题"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .JudgeNeedCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("判断题"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .SingleCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("单项选择题"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .SingleNeedCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("单项选择题"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .MultiCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("多项选择题"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .MultiNeedCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("多项选择题"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .InMultiCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("不定项"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .InMultiNeedCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("不定项"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .ComprehensiveCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("综合题"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .ComprehensiveNeedCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("综合题"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .BlankCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("填空题"))
                        .mapToInt(t -> t.getQuestionNum()).sum())
                .BlankNeedCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("填空题"))
                        .mapToInt(t -> t.getQuestionNum()).sum())
                .ShortAnswerCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("简答题"))
                        .mapToInt(t -> t.getQuestionNum()).sum())
                .ShortAnswerCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("简答题"))
                        .mapToInt(t -> t.getQuestionNum()).sum())
                .WriteCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("写作题"))
                        .mapToInt(t -> t.getQuestionNum()).sum())
                .WriteNeedCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("写作题"))
                        .mapToInt(t -> t.getQuestionNum()).sum())

                .FileCount(0)
                .PaperCount(1)
                .RepeatCount(0)
                .build();
        List<QuesTypeSort> QuesTypeSorts = new ArrayList<>();
        request.getQuestionTypes().forEach(t -> {
            QuesTypeSort qs = new QuesTypeSort();
            if (t.getQuestionType().equals("判断题")) {
                qs.setQuesType(1);
                qs.setQuesTypeName("判断题");
                qs.setSort((t.getOrder()));
            }
            if (t.getQuestionType().equals("单项选择题")) {
                qs.setQuesType(2);
                qs.setQuesTypeName("单项选择题");
                qs.setSort(t.getOrder());
            }
            if (t.getQuestionType().equals("多项选择题")) {
                qs.setQuesType(3);
                qs.setQuesTypeName("多项选择题");
                qs.setSort((t.getOrder()));
            }
            if (t.getQuestionType().equals("不定项")) {
                qs.setQuesType(4);
                qs.setQuesTypeName("不定项");
                qs.setSort(t.getOrder());
            }
            if (t.getQuestionType().equals("填空题")) {
                qs.setQuesType(5);
                qs.setQuesTypeName("填空题");
                qs.setSort(t.getOrder());
            }
            if (t.getQuestionType().equals("简答题")) {
                qs.setQuesType(6);
                qs.setQuesTypeName("简答题");
                qs.setSort(t.getOrder());
            }
            if (t.getQuestionType().equals("写作题")) {
                qs.setQuesType(8);
                qs.setQuesTypeName("写作题");
                qs.setSort(t.getOrder());
            }
            if (t.getQuestionType().equals("综合题")) {
                qs.setQuesType(10);
                qs.setQuesTypeName("综合题");
                qs.setSort(t.getOrder());
            }
            if (t.getQuestionType().equals("表格题")) {
                qs.setQuesType(11);
                qs.setQuesTypeName("表格题");
                qs.setSort(t.getOrder());
            }
            QuesTypeSorts.add(qs);
        });

        List<QuesTypeMemo> QuesTypeMemos = new ArrayList<>();
        request.getQuestionTypes().forEach(t -> {
            QuesTypeMemo m = new QuesTypeMemo();
            if (t.getQuestionType().equals("判断题")) {
                m.setQuesType(1);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("单项选择题")) {
                m.setQuesType(2);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("多项选择题")) {
                m.setQuesType(3);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("不定项")) {
                m.setQuesType(4);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("填空题")) {
                m.setQuesType(5);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("简答题")) {
                m.setQuesType(6);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("写作题")) {
                m.setQuesType(8);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("综合题")) {
                m.setQuesType(10);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("表格题")) {
                m.setQuesType(11);
                m.setMemo(t.getRemark());
            }

            QuesTypeMemos.add(m);
        });
        List<QuesTypeAlias> QuesTypeAliases = new ArrayList<>();
        request.getQuestionTypes().forEach(t -> {
            QuesTypeAlias m = new QuesTypeAlias();
            if (t.getQuestionType().equals("判断题")) {
                m.setQuesType(1);
                m.setQuesTypeName("判断题");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("单项选择题")) {
                m.setQuesType(2);
                m.setQuesTypeName("单项选择题");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("多项选择题")) {
                m.setQuesType(3);
                m.setQuesTypeName("多项选择题");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("不定项")) {
                m.setQuesType(4);
                m.setQuesTypeName("不定项");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("填空题")) {
                m.setQuesType(5);
                m.setQuesTypeName("填空题");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("简答题")) {
                m.setQuesType(6);
                m.setQuesTypeName("简答题");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("写作题")) {
                m.setQuesType(8);
                m.setQuesTypeName("写作题");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("综合题")) {
                m.setQuesType(10);
                m.setQuesTypeName("综合题");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("表格题")) {
                m.setQuesType(11);
                m.setQuesTypeName("表格题");
                m.setQuesTypeAlias(t.getAlias());
            }

            QuesTypeAliases.add(m);
        });
        paperDesc.setListQuesTypeSort(QuesTypeSorts);
        paperDesc.setListQuesTypeMemo(QuesTypeMemos);
        paperDesc.setListQuesTypeAlias(QuesTypeAliases);
        libraryVO libraryVO = new libraryVO();
        libraryVO.setPaperDesc(JSONObject .toJSONString(paperDesc));
        libraryVO.setLibraryId(project.getProjectId() + "_"+ subject.getKmxh() + "_" + ChineseNumberConverter.extractAndConvertChineseNumber(subject.getSessionName()));
        libraryVO.setExaminerId(0);
        libraryVO.setProjectId(0);
        libraryVO.setRoomLock(-1);
        libraryVO.setBatchId(0);
        libraryVO.setSubjectId(0);
        libraryVO.setKcid("");
        libraryVO.setCcid("");
        libraryVO.setCcsxh(0);
        libraryVO.setKmxh(subject.getKmxh());
        libraryVO.setIsSparePaper(0);
        libraryVO.setIsEncrypt(1);
        libraryVO.setIsImageEncrypt(1);
        libraryVO.setExaminerName("");
        libraryVO.setLibraryName(subject.getSubjectName());
        libraryVO.setLibraryType(1);
        libraryVO.setQuesCount(questionCount);
        libraryVO.setIsDisturb(1);
        libraryVO.setPaperLockedStatus(-1);
        libraryVO.setCreatedTime("");
        // 题目信息
        List<quesDtos> quesDtosList = new ArrayList<>();
        for (QuestionBanks question : questions) {
            quesDtos q = new quesDtos();
            q.setId(0);
            q.setProjectId(0);
            q.setLibraryId("");
            q.setInputType(0);
            q.setDifficultLevel(0);
            q.setQuesAnswer("");
            q.setQuesNo(question.getQuestionId());
            q.setQuesScore(Double.parseDouble(question.getScore()));
            if (question.getQuestionType().equals("判断题")){
                q.setQuesType(1);
            }
            if (question.getQuestionType().equals("单项选择题")){
                q.setQuesType(2);
            }
            if (question.getQuestionType().equals("多项选择题")){
                q.setQuesType(3);
            }
            if (question.getQuestionType().equals("不定项")){
                q.setQuesType(4);
            }
            if (question.getQuestionType().equals("填空题")){
                q.setQuesType(5);
                q.setChildCount(Integer.parseInt(question.getChildCount()));
            }
            if (question.getQuestionType().equals("简答题")){
                q.setQuesType(6);
                q.setChildCount(Integer.parseInt(question.getChildCount()));
            }
            if (question.getQuestionType().equals("写作题")){
                q.setQuesType(8);
                q.setChildCount(Integer.parseInt(question.getChildCount()));
            }
            if (question.getQuestionType().equals("综合题")){
                q.setQuesType(10);
                q.setChildCount(Integer.parseInt(question.getChildCount()));
            }
            if (question.getQuestionType().equals("表格题")){
                q.setQuesType(11);
            }

            String[] s = question.getQuestionId().split("_");
            if (question.getParentId() == null){
                q.setSort(Integer.parseInt(s[s.length-1]));
            }else {
                AtomicInteger counter = new AtomicInteger();
                q.setSort(counter.incrementAndGet());
            }
            q.setSort(Integer.parseInt(s[s.length-1]));
            List<files> Fileslist = new ArrayList();
            HtmlProcessor.ProcessResult processResult = HtmlProcessor.processHtmlBaseImages(question.getQuestionHtml(), imageDir, request.getEncryptPassword());
            Map<String, ImageDownloader.DownloadResult> imageDownloadResult = processResult.getImageDownloadResult();
            if (imageDownloadResult != null && imageDownloadResult.size() > 0) {
                imageDownloadResult.forEach((k, v) -> {
                    files f = new files();
                    f.setHashCode(v.getImageHash());
                    f.setFileName(k+ ".base64");
                    f.setFileType(6);
                    f.setLocation("0");
                    f.setFileSize("");
                    f.setFilePath(v.getEncryptedFilePath()+ ".base64");
                    Fileslist.add(f);
                });
                q.setFiles(JSONObject.toJSONString(Fileslist));
            }else {
                q.setFiles("[]");
            }
            if (question.getParentId() == null){
                q.setParentId("");
            }else {
                q.setParentId(question.getParentId());
            }
            // 如果为空就是设置成'0' 不为空就是设置值
            if (question.getChildCount() == null || question.getChildCount().equals("")){
                q.setChildCount(0);
            }else{
                q.setChildCount(Integer.parseInt(question.getChildCount()));
            }

            String questionHtml = AdvancedContentExtractor2.extractContentHTML2(question.getQuestionHtml().replaceAll(">\\s+<", "><"));
            String cleanedQuestionHtml = cleanQuestionHtml(questionHtml);
            q.setQuesTitle((AESDecryptor.encrypt(cleanedQuestionHtml,request.getEncryptPassword(),"0000000000000000")));
            String optionsHtml = question.getOptionsHtml();
            List<Options> optionHTMLList = Options.parseOptionsHTML(optionsHtml, request.getEncryptPassword());
            if ( optionHTMLList.size() == 0) {
                q.setOptions("");
            }else {
                q.setOptions(JSON.toJSONString(optionHTMLList));
            }
            quesDtosList.add(q);
            List<QuestionBanks> questionBanks = questionBanksService.findByParentId(question.getQuestionId());
            if (( question.getQuestionType().equals("综合题") || question.getQuestionType().equals("简答题") || question.getQuestionType().equals("写作题"))&&questionBanks.size()<=0 && question.getParentId().equals("") ){
                // 这个对象抽象成一个方法
                quesDtos quesDtos = getQuesDtos(question, q);
                quesDtosList.add(quesDtos);
            }

        }
        JSONArray ruleItems = new JSONArray();
        JSONArray listPaper = new JSONArray();
        JSONArray  listPaperQues = new JSONArray();

        config.put("kmxh",subject.getKmxh());
        config.put("libraryVO", libraryVO);
        config.put("quesItems", quesDtosList);
        config.put("ruleItems", ruleItems);
        config.put("listPaper", listPaper);
        config.put("listPaperQues", listPaperQues);
//        // 自定义 NameFilter，直接返回原始属性名
//        NameFilter nameFilter = (object, name, value) -> name;
//
//        // 使用自定义 NameFilter 进行序列化
//        String jsonString = JSON.toJSONString(config, nameFilter, SerializerFeature.PrettyFormat);
        String encodedToString = Base64.getEncoder().encodeToString(config.toString().getBytes());
        // 写入文件
        Files.write(tempDir.resolve("library.libr"),
                encodedToString.getBytes(StandardCharsets.UTF_8));
        return config;
    }

    /**
     *  生成试考包
     * @param project
     * @param subject
     * @param request
     * @param questions
     * @param tempDir
     * @param imageDir
     * @return
     * @throws Exception
     */
    private JSONObject generatePageFile(Projects project,
                                        SubjectSessions subject,
                                        PackageRequest request,
                                        List<QuestionBanks> questions,
                                        Path tempDir,
                                        Path imageDir) throws Exception {

        JSONObject config = new JSONObject(new LinkedHashMap<>());
        int questionCount = questionBanksService.getQuestionCountBySubjectId(subject.getSubjectId());
        // 1. 生成配置文件
        CandidateDto candidateDto = CandidateDto.builder()
                .kmmc(subject.getSubjectName())
                .build();
        ProjectDto projectDto = ProjectDto.builder()
                .projectName(project.getProjectName())
                .unzipPassword(request.getPassword())
                .testEncryptKey(request.getEncryptPassword()).build();
        BatchDto batchDto = BatchDto.builder()
                .encryptKey(AESDecryptor.encrypt(request.getEncryptPassword(),"1234567890123456","1234567890123456"))
                .encryptResult(AESDecryptor.encrypt("1234567890","1234567890123456","0000000000000000"))
                .build();
        SubjectDto subjectDto = SubjectDto.builder()
                .subjectName(subject.getSubjectName())
                .kmjc(subject.getSubjectName())
                .build();
        BatchSubjectDto batchSubjectDto = BatchSubjectDto.builder().build();
        LibraryDto libraryDto = LibraryDto.builder().build();
        PaperDesc paperDesc = PaperDesc.builder()
                .TotalScore(request.getTotalScore())
                .TotalCount(questionCount)
                .TotalNeedCount(questionCount)
                .Kmxh(subject.getKmxh())
                .MakeupPaperType(0)

                .JudgeCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("判断题"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .JudgeNeedCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("判断题"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .SingleCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("单项选择题"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .SingleNeedCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("单项选择题"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .MultiCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("多项选择题"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .MultiNeedCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("多项选择题"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .InMultiCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("不定项"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .InMultiNeedCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("不定项"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .BlankCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("填空题"))
                        .mapToInt(t -> t.getQuestionNum()).sum())
                .BlankNeedCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("填空题"))
                        .mapToInt(t -> t.getQuestionNum()).sum())
                .ShortAnswerCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("简答题"))
                        .mapToInt(t -> t.getQuestionNum()).sum())
                .ShortAnswerNeedCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("简答题"))
                        .mapToInt(t -> t.getQuestionNum()).sum())
                .WriteCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("写作题"))
                        .mapToInt(t -> t.getQuestionNum()).sum())
                .WriteNeedCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("写作题"))
                        .mapToInt(t -> t.getQuestionNum()).sum())
                .ComprehensiveCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("综合题"))
                        .mapToInt(t -> t.getQuestionNum())
                        .sum())
                .ComprehensiveNeedCount(request.getQuestionTypes().stream()
                        .filter(t -> t.getQuestionType().equals("综合题"))
                        .mapToInt(t -> t.getQuestionNum()).sum())
                .RepeatCount(0)
                .build();
        List<QuesTypeSort> QuesTypeSorts = new ArrayList<>();
        request.getQuestionTypes().forEach(t -> {
            QuesTypeSort qs = new QuesTypeSort();
            if (t.getQuestionType().equals("判断题")) {
                qs.setQuesType(1);
                qs.setQuesTypeName("判断题");
                qs.setSort((t.getOrder()));
            }
            if (t.getQuestionType().equals("单项选择题")) {
                qs.setQuesType(2);
                qs.setQuesTypeName("单项选择题");
                qs.setSort(t.getOrder());
            }
            if (t.getQuestionType().equals("多项选择题")) {
                qs.setQuesType(3);
                qs.setQuesTypeName("多项选择题");
                qs.setSort((t.getOrder()));
            }
            if (t.getQuestionType().equals("不定项")) {
                qs.setQuesType(4);
                qs.setQuesTypeName("不定项");
                qs.setSort(t.getOrder());
            }
            if (t.getQuestionType().equals("填空题")) {
                qs.setQuesType(5);
                qs.setQuesTypeName("填空题");
                qs.setSort(t.getOrder());
            }
            if (t.getQuestionType().equals("简答题")) {
                qs.setQuesType(6);
                qs.setQuesTypeName("简答题");
                qs.setSort(t.getOrder());
            }
            if (t.getQuestionType().equals("写作题")) {
                qs.setQuesType(8);
                qs.setQuesTypeName("写作题");
                qs.setSort(t.getOrder());
            }
            if (t.getQuestionType().equals("综合题")) {
                qs.setQuesType(10);
                qs.setQuesTypeName("综合题");
                qs.setSort(t.getOrder());
            }
            if (t.getQuestionType().equals("表格题")) {
                qs.setQuesType(11);
                qs.setQuesTypeName("表格题");
                qs.setSort(t.getOrder());
            }
            QuesTypeSorts.add(qs);
        });


        List<QuesTypeMemo> QuesTypeMemos = new ArrayList<>();
        request.getQuestionTypes().forEach(t -> {
            QuesTypeMemo m = new QuesTypeMemo();
            if (t.getQuestionType().equals("判断题")) {
                m.setQuesType(1);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("单项选择题")) {
                m.setQuesType(2);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("多项选择题")) {
                m.setQuesType(3);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("不定项")) {
                m.setQuesType(4);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("填空题")) {
                m.setQuesType(5);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("简答题")) {
                m.setQuesType(6);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("写作题")) {
                m.setQuesType(8);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("综合题")) {
                m.setQuesType(10);
                m.setMemo(t.getRemark());
            }
            if (t.getQuestionType().equals("表格题")) {
                m.setQuesType(11);
                m.setMemo(t.getRemark());
            }
            QuesTypeMemos.add(m);
        });
        List<QuesTypeAlias> QuesTypeAliases = new ArrayList<>();
        request.getQuestionTypes().forEach(t -> {
            QuesTypeAlias m = new QuesTypeAlias();
            if (t.getQuestionType().equals("判断题")) {
                m.setQuesType(1);
                m.setQuesTypeName("判断题");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("单项选择题")) {
                m.setQuesType(2);
                m.setQuesTypeName("单项选择题");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("多项选择题")) {
                m.setQuesType(3);
                m.setQuesTypeName("多项选择题");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("不定项")) {
                m.setQuesType(4);
                m.setQuesTypeName("不定项");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("填空题")) {
                m.setQuesType(5);
                m.setQuesTypeName("填空题");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("简答题")) {
                m.setQuesType(6);
                m.setQuesTypeName("简答题");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("写作题")) {
                m.setQuesType(8);
                m.setQuesTypeName("写作题");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("综合题")) {
                m.setQuesType(10);
                m.setQuesTypeName("综合题");
                m.setQuesTypeAlias(t.getAlias());
            }
            if (t.getQuestionType().equals("表格题")) {
                m.setQuesType(11);
                m.setQuesTypeName("表格题");
                m.setQuesTypeAlias(t.getAlias());
            }

            QuesTypeAliases.add(m);
        });
        paperDesc.setListQuesTypeSort(QuesTypeSorts);
        paperDesc.setListQuesTypeMemo(QuesTypeMemos);
        paperDesc.setListQuesTypeAlias(QuesTypeAliases);

        // 题目信息
        List<quesDtos> quesDtosList = new ArrayList<>();
        for (QuestionBanks question : questions) {
            quesDtos q = new quesDtos();
            q.setId(0);
            q.setProjectId(0);
            q.setLibraryId("test_library_id");
            q.setInputType(0);
            q.setDifficultLevel(0);
            q.setQuesNo(question.getQuestionId());
            q.setQuesScore(Double.parseDouble(question.getScore()));
            if (question.getQuestionType().equals("计算题")){
                q.setQuesType(6);
            }else {
                q.setQuesType(QuestionTypeEnum.getCodeByName(question.getQuestionType()));
            }
            String[] s = question.getQuestionId().split("_");
            if (question.getParentId() == null){
                q.setSort(Integer.parseInt(s[s.length-1]));
            }else {
                AtomicInteger counter = new AtomicInteger();
                q.setSort(counter.incrementAndGet());
            }
            q.setSort(Integer.parseInt(s[s.length-1]));
            List<files> Fileslist = new ArrayList();
            HtmlProcessor.ProcessResult processResult = HtmlProcessor.processHtmlBaseImages(question.getQuestionHtml(), imageDir, request.getEncryptPassword());
            Map<String, ImageDownloader.DownloadResult> imageDownloadResult = processResult.getImageDownloadResult();
            if (imageDownloadResult != null && imageDownloadResult.size() > 0) {
                imageDownloadResult.forEach((k, v) -> {
                    files f = new files();
                    f.setHashCode(v.getImageHash());
                    f.setFileName(k+ ".base64");
                    f.setFileType(6);
                    f.setLocation("0");
                    f.setFileSize("");
                    f.setFilePath(v.getEncryptedFilePath()+ ".base64");
                    Fileslist.add(f);
                });
                q.setFiles(JSONObject.toJSONString(Fileslist));
            }else {
                q.setFiles("[]");
            }
            if (question.getParentId() == null){
                q.setParentId("");
            }else {
                q.setParentId(question.getParentId());
            }
            // 如果为空就是设置成'0' 不为空就是设置值
            if (question.getChildCount() == null || question.getChildCount().equals("")){
                q.setChildCount(0);
            }else{
                q.setChildCount(Integer.parseInt(question.getChildCount()));
            }

            String questionHtml = AdvancedContentExtractor2.extractContentHTML2(question.getQuestionHtml().replaceAll(">\\s+<", "><"));
            String cleanedQuestionHtml = cleanQuestionHtml(questionHtml);
            q.setQuesTitle( AESDecryptor.encrypt(cleanedQuestionHtml,request.getEncryptPassword(),"0000000000000000") );
            String optionsHtml = question.getOptionsHtml();
            List<Options> optionHTMLList = Options.parseOptionsHTML(optionsHtml, request.getEncryptPassword());
           if ( optionHTMLList.size() == 0) {
                q.setOptions("");
            }else {
                q.setOptions(JSON.toJSONString(optionHTMLList));
            }
            quesDtosList.add(q);
            List<QuestionBanks> questionBanks = questionBanksService.findByParentId(question.getQuestionId());
            // 没有小题的综合题和简答题
            if (( question.getQuestionType().equals("综合题") || question.getQuestionType().equals("简答题") || question.getQuestionType().equals("写作题"))&&questionBanks.size()<=0 && question.getParentId().equals("") ){
               // 这个对象抽象成一个方法
                quesDtos quesDtos = getQuesDtos(question, q);
                quesDtosList.add(quesDtos);
            }
        }


        config.put("candidateDto", candidateDto);
        config.put("projectDto", projectDto);
        config.put("batchDto", batchDto);
        config.put("batchSubjectDto", batchSubjectDto);
        config.put("subjectDto", subjectDto);
        config.put("libraryDto", libraryDto);
        config.put("paperDesc", paperDesc);
        config.put("quesDtos", quesDtosList);
//        // 自定义 NameFilter，直接返回原始属性名
//        NameFilter nameFilter = (object, name, value) -> name;
//
//        // 使用自定义 NameFilter 进行序列化
//        String jsonString = JSON.toJSONString(config, nameFilter, SerializerFeature.PrettyFormat);

        // 写入文件
        Files.write(tempDir.resolve("1512101001001.json"),
                config.toString().getBytes(StandardCharsets.UTF_8));
        return config;
    }
    // 这个对象抽象成一个方法

    private quesDtos getQuesDtos(QuestionBanks question,quesDtos q) {
        String[] s = question.getQuestionId().split("_");
        quesDtos quesDtos = new quesDtos();
        quesDtos.setQuesType(6);
        quesDtos.setId(0);
        quesDtos.setProjectId(0);
        quesDtos.setLibraryId("test_library_id");
        quesDtos.setParentId(q.getQuesNo());
        quesDtos.setQuesNo(q.getQuesNo() + "_1");
        quesDtos.setChildCount(0);
        quesDtos.setInputType(0);
        quesDtos.setDifficultLevel(0);
        quesDtos.setQuesScore(Double.parseDouble(question.getScore()));
        quesDtos.setSort(1);
        quesDtos.setFiles("[]");
        quesDtos.setQuesTitle("");
        quesDtos.setQuesTitleTail("");
        quesDtos.setQuesAnswer("");
        quesDtos.setOptions("");
        quesDtos.setKnowledgeId("");
        return quesDtos;
    }
    private ExamData generateLoginFile(Path tempDir) throws IOException {
        JSONObject config = new JSONObject();
        ExamData examData = new ExamData();
        examData.setProjectId(1002);
        examData.setBatchId(1003);
        examData.setSubjectId(1004);
        examData.setLoginCount(0);
        examData.setBeginTime("2024-07-16T14:54:38.1442658+08:00");
        examData.setBatchBeginTime("2024-07-16T14:54:38.1442658+08:00");
        examData.setRealBeginTime("");
        examData.setTotalMinute(150);
        examData.setPlusMinute(0);
        examData.setRemainingSecond(9000);
        examData.setTotalScore(-1.0);
        examData.setRoomLock(0);
        examData.setCandiNumber("1512101001001");
        examData.setCertificateNumber("440121199504253258");
        examData.setCandiName("张三");
        examData.setToken("");
        examData.setExamStatus(1);
        examData.setBatchExamStatus(0);
        examData.setSeatNumber(0);
        examData.setAllowBeginExam(true);
        examData.setAnswerContentCheckCode("");
        examData.setMemo("");
        examData.setCompleteCount(0);
        examData.setDelayMillSecond(1);
        examData.setAutotestingRepeatTimes(0);
        examData.setAutotestingNextSpan(0);
        examData.setNextCandiNumber("");
        examData.setTestingTime("2022-12-17 11:00-08:30");
        examData.setSingleExportTime("2024-07-16 14:54:38");


        String examDataJson = JSON.toJSONString(examData);
        // 写入文件
        Files.write(tempDir.resolve("1512101001001.login"),
                examDataJson.getBytes(StandardCharsets.UTF_8));
        return examData;
    }
    /**
     * 从包含数字点 + 内容格式的字符串中提取内容部分
     * @param input 包含数字点 + 内容格式的字符串
     * @return 提取出的内容字符串
     */

    public String extractContent(String input) {
        // 定义正则表达式，匹配数字和点号，然后替换为空字符串
        String result = input.replaceFirst("^\\d+[\\.．,，]\\s*", "");
        return result.trim();
    }






    private Path createTempDirectory(String path) throws IOException {
        Path tempDir = Paths.get(path);
        Files.createDirectories(tempDir);
        return tempDir;
    }






    private void zipFiles(Path sourceDir, HttpServletResponse response) throws IOException {
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=exam_package.zip");

        try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
             Stream<Path> paths = Files.walk(sourceDir)) {

            paths.filter(path -> !Files.isDirectory(path))
                    .forEach(path -> {
                        ZipEntry zipEntry = new ZipEntry(sourceDir.relativize(path).toString());
                        try {
                            zos.putNextEntry(zipEntry);
                            Files.copy(path, zos);
                            zos.closeEntry();
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    });
        }
    }






}
